#include "UdpThread.h"
#define SERVER_PORT 1025

UdpThread::UdpThread(QObject *parent) : QThread(parent)
{
    udpSocket = new QUdpSocket(this);
}

void UdpThread::run()
{
    QUdpSocket socket;
    if (!socket.bind(SERVER_PORT)) {
        qDebug() << "Could not bind socket!";
        return;
    }

    while (!isInterruptionRequested()) {
        if (socket.hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(socket.pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            socket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
            emit messageReceived(datagram, sender, senderPort);
        }
        QThread::msleep(10); // Avoid high CPU usage
    }
}

void UdpThread::sendMessage(const QByteArray &message, const QHostAddress &address, quint16 port)
{
    udpSocket->writeDatagram(message, address, port);
}
